<template>
  <view class="dashboard-container">
    <!-- 状态栏占位 -->
    <view :style="{ height: statusBarHeight + 'px' }"></view>
    
    <!-- 页面标题 -->
    <view class="page-header">
      <view class="title-section">
        <text class="page-title">智能货架管理</text>
        <text class="date">{{ currentDate }}</text>
      </view>
      <view class="refresh-btn" @click="refreshData">
        <uni-icons type="refresh" size="18" color="#FF8C42"></uni-icons>
      </view>
    </view>
    
    <!-- 统计概览部分 -->
    <view class="stats-overview">
      <view class="stats-grid">
        <!-- 贩卖机总数 -->
        <view class="stat-card">
          <view class="stat-icon machine-icon">
            <uni-icons type="shop" size="24" color="#FF8C42"></uni-icons>
          </view>
          <view class="stat-content">
            <text class="stat-label">贩卖机总数</text>
            <text class="stat-value">{{ dashboardData.totalMachines }}</text>
          </view>
        </view>
        
        <!-- 商品总数 -->
        <view class="stat-card">
          <view class="stat-icon product-icon">
            <uni-icons type="gift" size="24" color="#FF8C42"></uni-icons>
          </view>
          <view class="stat-content">
            <text class="stat-label">商品总数</text>
            <text class="stat-value">{{ dashboardData.totalProducts }}</text>
          </view>
        </view>
        
        <!-- 今日销量 -->
        <view class="stat-card">
          <view class="stat-icon sales-icon">
            <uni-icons type="cart" size="24" color="#FF8C42"></uni-icons>
          </view>
          <view class="stat-content">
            <text class="stat-label">今日销量</text>
            <text class="stat-value">{{ dashboardData.todaySales }}</text>
          </view>
        </view>
        
        <!-- 库存预警 -->
        <view class="stat-card">
          <view class="stat-icon warning-icon">
            <uni-icons type="notification" size="24" color="#FF8C42"></uni-icons>
          </view>
          <view class="stat-content">
            <text class="stat-label">库存预警</text>
            <text class="stat-value">{{ dashboardData.lowStockCount }}</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 贩卖机库存状态 -->
    <view class="machines-section">
      <view class="section-header">
        <view class="section-title">
          <text>贩卖机库存状态</text>
        </view>
        <view class="view-all" @click="navigateTo('allMachines')">
          <text>查看全部</text>
          <uni-icons type="right" size="14" color="#999"></uni-icons>
        </view>
      </view>
      
      <scroll-view scroll-x="true" class="machines-scroll">
        <view class="machines-container">
          <view 
            v-for="machine in dashboardData.machines" 
            :key="machine.id" 
            class="machine-card"
            @click="viewMachineDetail(machine.id)"
          >
            <view class="machine-header">
              <view class="machine-name">{{ machine.name }}</view>
              <view :class="['machine-status', machine.status === 'online' ? 'status-online' : 'status-offline']">
                {{ machine.status === 'online' ? '在线' : '离线' }}
              </view>
            </view>
            <view class="machine-location">{{ machine.location }}</view>
            <view class="machine-stats">
              <view class="machine-stat">
                <text class="stat-label">商品数</text>
                <text class="stat-value">{{ machine.productCount }}</text>
              </view>
              <view class="machine-stat">
                <text class="stat-label">库存率</text>
                <text class="stat-value">{{ machine.stockPercentage }}%</text>
              </view>
              <view class="machine-stat">
                <text class="stat-label">今日销量</text>
                <text class="stat-value">{{ machine.todaySales }}</text>
              </view>
            </view>
            <view class="stock-bar">
              <view 
                class="stock-progress" 
                :style="{ width: machine.stockPercentage + '%', backgroundColor: getStockColor(machine.stockPercentage) }"
              ></view>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
    
    <!-- 商品销售对比 -->
    <view class="products-section">
      <view class="section-header">
        <view class="section-title">
          <text>商品销售对比</text>
        </view>
        <view class="view-all" @click="navigateTo('allProducts')">
          <text>查看全部</text>
          <uni-icons type="right" size="14" color="#999"></uni-icons>
        </view>
      </view>
      
      <view class="products-list">
        <view 
          v-for="(product, index) in dashboardData.topProducts" 
          :key="product.id" 
          class="product-item"
          @click="viewProductDetail(product.id)"
        >
          <view class="product-rank">{{ index + 1 }}</view>
          <image class="product-image" :src="product.image" mode="aspectFill"></image>
          <view class="product-info">
            <view class="product-name">{{ product.name }}</view>
            <view class="product-category">{{ product.category }}</view>
          </view>
          <view class="product-sales">
            <text class="sales-value">{{ product.sales }}</text>
            <text class="sales-label">件</text>
          </view>
          <view class="sales-bar-container">
            <view 
              class="sales-bar" 
              :style="{ width: (product.sales / getMaxSales() * 100) + '%' }"
            ></view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 库存预警商品 -->
    <view class="warning-section" v-if="dashboardData.lowStockProducts.length > 0">
      <view class="section-header">
        <view class="section-title">
          <text>库存预警商品</text>
        </view>
        <view class="view-all" @click="navigateTo('lowStock')">
          <text>查看全部</text>
          <uni-icons type="right" size="14" color="#999"></uni-icons>
        </view>
      </view>
      
      <view class="warning-list">
        <view 
          v-for="product in dashboardData.lowStockProducts" 
          :key="product.id" 
          class="warning-item"
          @click="replenishStock(product.id)"
        >
          <image class="warning-image" :src="product.image" mode="aspectFill"></image>
          <view class="warning-info">
            <view class="warning-name">{{ product.name }}</view>
            <view class="warning-location">{{ product.machineName }}</view>
          </view>
          <view class="warning-stock">
            <text class="warning-value">{{ product.stock }}</text>
            <text class="warning-label">剩余</text>
          </view>
          <view class="replenish-btn">补货</view>
        </view>
      </view>
    </view>
    
    <!-- 用户类型管理 -->
    <user-type-manager></user-type-manager>
    
    <!-- 底部导航栏 -->
    <tab-bar :active="0"></tab-bar>
  </view>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue';
import { useUserStore } from '@/store/user';
import UserTypeManager from '@/components/user-type-manager.vue';
import TabBar from '@/components/tab-bar.vue';


// 声明 uni 变量
// declare var uni: any;

export default {
  components: {
    UserTypeManager,
    TabBar
  },
  setup() {
    // 状态栏高度
    const statusBarHeight = ref(0);

// 用户状态
const userStore = useUserStore();
    // 获取状态栏高度
    const getStatusBarHeight = () => {
      try {
        const systemInfo = uni.getSystemInfoSync();
        statusBarHeight.value = systemInfo.statusBarHeight || 0;
      } catch (e) {
        console.error('获取系统信息失败:', e);
        statusBarHeight.value = 0;
      }
    };

    // 获取当前日期
    const currentDate = computed(() => {
      const now = new Date();
      const year = now.getFullYear();
      const month = now.getMonth() + 1;
      const day = now.getDate();
      return `${year}年${month}月${day}日`;
    });

    // 仪表盘数据（静态数据）
    const dashboardData = reactive({
      totalMachines: 12,
      totalProducts: 86,
      todaySales: 243,
      lowStockCount: 8,

      // 贩卖机数据
      machines: [
        {
          id: 1,
          name: '智能货架 #A001',
          location: '科技园区1号楼大厅',
          status: 'online',
          productCount: 24,
          stockPercentage: 85,
          todaySales: 42
        },
        {
          id: 2,
          name: '智能货架 #A002',
          location: '科技园区2号楼一层',
          status: 'online',
          productCount: 18,
          stockPercentage: 62,
          todaySales: 36
        },
        {
          id: 3,
          name: '智能货架 #B001',
          location: '商业中心购物广场',
          status: 'online',
          productCount: 32,
          stockPercentage: 91,
          todaySales: 78
        },
        {
          id: 4,
          name: '智能货架 #B002',
          location: '商业中心地下一层',
          status: 'offline',
          productCount: 12,
          stockPercentage: 45,
          todaySales: 23
        },
        {
          id: 5,
          name: '智能货架 #C001',
          location: '创业园区3号楼',
          status: 'online',
          productCount: 28,
          stockPercentage: 76,
          todaySales: 64
        }
      ],

      // 热销商品数据
      topProducts: [
        {
          id: 101,
          name: '矿泉水 550ml',
          category: '饮料',
          sales: 86,
          image: '/static/products/water.png'
        },
        {
          id: 102,
          name: '可口可乐 330ml',
          category: '饮料',
          sales: 72,
          image: '/static/products/cola.png'
        },
        {
          id: 103,
          name: '巧克力威化饼干',
          category: '零食',
          sales: 65,
          image: '/static/products/chocolate.png'
        },
        {
          id: 104,
          name: '薯片原味 100g',
          category: '零食',
          sales: 58,
          image: '/static/products/chips.png'
        },
        {
          id: 105,
          name: '绿茶 500ml',
          category: '饮料',
          sales: 45,
          image: '/static/products/tea.png'
        }
      ],

      // 库存预警商品
      lowStockProducts: [
        {
          id: 201,
          name: '矿泉水 550ml',
          machineName: '智能货架 #A001',
          stock: 2,
          image: '/static/products/water.png'
        },
        {
          id: 202,
          name: '薯片原味 100g',
          machineName: '智能货架 #B001',
          stock: 3,
          image: '/static/products/chips.png'
        },
        {
          id: 203,
          name: '巧克力威化饼干',
          machineName: '智能货架 #A002',
          stock: 1,
          image: '/static/products/chocolate.png'
        }
      ]
    });

    // 获取库存颜色
    const getStockColor = (percentage) => {
      if (percentage >= 70) return '#10B981'; // 绿色
      if (percentage >= 30) return '#F59E0B'; // 黄色
      return '#EF4444'; // 红色
    };

    // 获取最大销售量（用于计算销售条形图宽度）
    const getMaxSales = () => {
      let max = 0;
      dashboardData.topProducts.forEach(product => {
        if (product.sales > max) max = product.sales;
      });
      return max;
    };

    // 刷新数据
    const refreshData = () => {
      uni.showLoading({
        title: '刷新中...'
      });

      // 模拟数据刷新
      setTimeout(() => {
        // 随机更新今日销量
        dashboardData.todaySales = Math.floor(Math.random() * 50) + 200;

        // 随机更新贩卖机销量
        dashboardData.machines.forEach(machine => {
          machine.todaySales = Math.floor(Math.random() * 20) + 20;
          machine.stockPercentage = Math.floor(Math.random() * 30) + 70;
        });

        uni.hideLoading();
        uni.showToast({
          title: '数据已刷新',
          icon: 'success'
        });
      }, 800);
    };

    // 页面导航
	
	
    const navigateTo = (page) => {
      const pageMap = {
        'allMachines': '/pages/merchant/machines/list',
        'allProducts': '/pages/merchant/products/list',
        'lowStock': '/pages/merchant/inventory/low-stock'
      };
	  

      const url = pageMap[page];
      if (url) {
        uni.showToast({
          title: '看你妈',
          icon: 'none'
        });
      }
    };

    // 查看贩卖机详情
    const viewMachineDetail = (machineId) => {
      uni.showToast({
        title: `查看贩卖机ID: ${machineId}`,
        icon: 'none'
      });
    };

    // 查看商品详情
    const viewProductDetail = (productId) => {
      uni.showToast({
        title: `查看商品ID: ${productId}`,
        icon: 'none'
      });
    };

    // 补货操作
    const replenishStock = (productId) => {
      uni.showModal({
        title: '补货确认',
        content: '是否确认为该商品补货？',
        success: (res) => {
          if (res.confirm) {
            uni.showToast({
              title: '补货请求已提交',
              icon: 'success'
            });

            // 模拟补货后更新数据
            const index = dashboardData.lowStockProducts.findIndex(item => item.id === productId);
            if (index !== -1) {
              dashboardData.lowStockProducts.splice(index, 1);
              dashboardData.lowStockCount -= 1;
            }
          }
        }
      });
    };

    // 页面加载时执行
    onMounted(() => {
      console.log('零售货架系统商家仪表盘页面加载完成');
      // 获取状态栏高度
      getStatusBarHeight();

      // 初始化用户状态
      userStore.initUserState();

      // 如果用户不是商家，提示切换身份
      if (!userStore.isMerchant()) {
        uni.showModal({
          title: '提示',
          content: '您当前不是商家身份，是否切换为商家身份？',
          success: (res) => {
            if (res.confirm) {
              // 模拟商家登录
              const merchantInfo = {
                id: 'M' + Math.floor(Math.random() * 10000),
                username: '示例商家',
                storeName: '智能货架管理中心',
                phone: '13800138000'
              };
              userStore.login('merchant', merchantInfo);
            } else {
              // 用户取消，返回用户首页
              uni.redirectTo({
                url: '/pages/index/index'
              });
            }
          }
        });
      }

      // 替换默认图片路径为占位图
      dashboardData.topProducts.forEach(product => {
        product.image = `/placeholder.svg?height=80&width=80&text=${encodeURIComponent(product.name)}`;
      });

      dashboardData.lowStockProducts.forEach(product => {
        product.image = `/placeholder.svg?height=60&width=60&text=${encodeURIComponent(product.name)}`;
      });
    });

    return {
      statusBarHeight,
      currentDate,
      dashboardData,
      getStockColor,
      getMaxSales,
      refreshData,
      navigateTo,
      viewMachineDetail,
      viewProductDetail,
      replenishStock,
      userStore
    }
  }
}
</script>

<style>
.dashboard-container {
  padding-bottom: 120rpx; /* 增加底部padding，为底部导航栏留出空间 */
  background-color: #FFF9F2; /* 与首页一致的背景色 */
  min-height: 100vh;
}

.page-header {
  padding: 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #FFFFFF;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  border-bottom: 1rpx solid #FFE6CC; /* 与首页一致的边框 */
}

.title-section {
  display: flex;
  flex-direction: column;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333333;
}

.date {
  font-size: 24rpx;
  color: #999999;
  margin-top: 6rpx;
}

.refresh-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #FFF0E0; /* 与首页一致的按钮背景色 */
  border-radius: 30rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  padding: 0 30rpx;
}

.section-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333333;
  position: relative;
  padding-left: 20rpx;
}

.section-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 6rpx;
  height: 30rpx;
  background-color: #FF8C42; /* 与首页一致的强调色 */
  border-radius: 3rpx;
}

.view-all {
  display: flex;
  align-items: center;
  font-size: 24rpx;
  color: #999999;
}

.stats-overview {
  padding: 20rpx 30rpx;
}

.stats-grid {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -10rpx;
}

.stat-card {
  width: calc(100% - 20rpx);
  margin: 10rpx;
  background-color: #FFFFFF;
  border-radius: 16rpx;
  padding: 20rpx;
  display: flex;
  align-items: center;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  border: 1rpx solid #FFE6CC; /* 与首页一致的边框 */
}

.stat-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 40rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 20rpx;
}

.machine-icon {
  background-color: #FFF0E0; /* 与首页一致的图标背景色 */
}

.product-icon {
  background-color: #FFF0E0; /* 与首页一致的图标背景色 */
}

.sales-icon {
  background-color: #FFF0E0; /* 与首页一致的图标背景色 */
}

.warning-icon {
  background-color: #FFF0E0; /* 与首页一致的图标背景色 */
}

.stat-content {
  flex: 1;
}

.stat-label {
  font-size: 24rpx;
  color: #666666;
  display: block;
  margin-bottom: 10rpx;
}

.stat-value {
  font-size: 36rpx;
  font-weight: bold;
  color: #333333;
  display: block;
}

/* 贩卖机部分 */
.machines-section {
  margin-top: 30rpx;
  padding-bottom: 20rpx;
}

.machines-scroll {
  width: 100%;
  white-space: nowrap;
}

.machines-container {
  padding: 0 20rpx;
  display: inline-flex;
}

.machine-card {
  width: 300rpx;
  background-color: #FFFFFF;
  border-radius: 16rpx;
  padding: 20rpx;
  margin-right: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  display: inline-block;
  border: 1rpx solid #FFE6CC; /* 与首页一致的边框 */
}

.machine-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
}

.machine-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333333;
}

.machine-status {
  font-size: 22rpx;
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
}

.status-online {
  background-color: #D1FAE5;
  color: #10B981;
}

.status-offline {
  background-color: #F3F4F6;
  color: #6B7280;
}

.machine-location {
  font-size: 22rpx;
  color: #666666;
  margin-bottom: 15rpx;
  white-space: normal;
  height: 60rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.machine-stats {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15rpx;
}

.machine-stat {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.machine-stat .stat-label {
  font-size: 20rpx;
  margin-bottom: 5rpx;
}

.machine-stat .stat-value {
  font-size: 26rpx;
}

.stock-bar {
  height: 8rpx;
  background-color: #FFE6CC; /* 与首页一致的进度条背景色 */
  border-radius: 4rpx;
  overflow: hidden;
}

.stock-progress {
  height: 100%;
  border-radius: 4rpx;
}

/* 商品销售对比部分 */
.products-section {
  margin-top: 30rpx;
}

.products-list {
  background-color: #FFFFFF;
  border-radius: 16rpx;
  margin: 0 30rpx;
  padding: 10rpx 0;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  border: 1rpx solid #FFE6CC; /* 与首页一致的边框 */
}

.product-item {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  position: relative;
  border-bottom: 1rpx solid #FFE6CC; /* 与首页一致的分隔线 */
}

.product-item:last-child {
  border-bottom: none;
}

.product-rank {
  width: 40rpx;
  height: 40rpx;
  background-color: #FFF0E0; /* 与首页一致的背景色 */
  border-radius: 20rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24rpx;
  font-weight: bold;
  color: #FF8C42; /* 与首页一致的文字颜色 */
  margin-right: 20rpx;
}

.product-item:nth-child(1) .product-rank {
  background-color: #FEF3C7;
  color: #F59E0B;
}

.product-item:nth-child(2) .product-rank {
  background-color: #E5E7EB;
  color: #6B7280;
}

.product-item:nth-child(3) .product-rank {
  background-color: #FEE2E2;
  color: #EF4444;
}

.product-image {
  width: 80rpx;
  height: 80rpx;
  border-radius: 10rpx;
  margin-right: 20rpx;
  background-color: #FFF0E0; /* 与首页一致的背景色 */
}

.product-info {
  flex: 1;
  margin-right: 20rpx;
}

.product-name {
  font-size: 28rpx;
  color: #333333;
  margin-bottom: 5rpx;
}

.product-category {
  font-size: 22rpx;
  color: #666666;
}

.product-sales {
  margin-right: 20rpx;
  text-align: right;
  min-width: 60rpx;
}

.sales-value {
  font-size: 28rpx;
  font-weight: bold;
  color: #FF8C42; /* 与首页一致的强调色 */
}

.sales-label {
  font-size: 22rpx;
  color: #666666;
  margin-left: 5rpx;
}

.sales-bar-container {
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 4rpx;
  background-color: #FFE6CC; /* 与首页一致的进度条背景色 */
}

.sales-bar {
  height: 100%;
  background-color: #FF8C42; /* 与首页一致的强调色 */
}

/* 库存预警部分 */
.warning-section {
  margin-top: 30rpx;
  margin-bottom: 30rpx;
}

.warning-list {
  background-color: #FFFFFF;
  border-radius: 16rpx;
  margin: 0 30rpx;
  padding: 10rpx 0;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  border: 1rpx solid #FFE6CC; /* 与首页一致的边框 */
}

.warning-item {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #FFE6CC; /* 与首页一致的分隔线 */
}

.warning-item:last-child {
  border-bottom: none;
}

.warning-image {
  width: 60rpx;
  height: 60rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
  background-color: #FFF0E0; /* 与首页一致的背景色 */
}

.warning-info {
  flex: 1;
  margin-right: 20rpx;
}

.warning-name {
  font-size: 28rpx;
  color: #333333;
  margin-bottom: 5rpx;
}

.warning-location {
  font-size: 22rpx;
  color: #666666;
}

.warning-stock {
  margin-right: 20rpx;
  text-align: right;
}

.warning-value {
  font-size: 28rpx;
  font-weight: bold;
  color: #EF4444;
}

.warning-label {
  font-size: 22rpx;
  color: #666666;
  margin-left: 5rpx;
}

.replenish-btn {
  padding: 10rpx 20rpx;
  background-color: #FFF0E0; /* 与首页一致的按钮背景色 */
  color: #FF8C42; /* 与首页一致的按钮文字颜色 */
  font-size: 24rpx;
  border-radius: 30rpx;
  border: 1rpx solid #FFE6CC; /* 与首页一致的边�� */
}
</style>